package com.marketingexpert.service.storemgnt.taobao;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.springframework.mail.MailAuthenticationException;

import com.marketingexpert.config.Configuration;
import com.marketingexpert.config.SystemErrorCode;
import com.marketingexpert.exception.MarketingExpertException;
import com.marketingexpert.service.storemgnt.AbstractActivity;
import com.marketingexpert.service.storemgnt.ArticleUserSubscribe;
import com.marketingexpert.service.storemgnt.MarketingPromotion;
import com.marketingexpert.service.storemgnt.StoreService;
import com.marketingexpert.service.storemgnt.SubscribeService;
import com.marketingexpert.service.storemgnt.taobao.domain.impl.AbstractActivityTaobaoImpl;
import com.marketingexpert.service.storemgnt.taobao.domain.impl.TaobaoItem;
import com.marketingexpert.service.storemgnt.taobao.domain.impl.TaobaoPromotion;
import com.marketingexpert.util.Resources;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.TaobaoResponse;
import com.taobao.api.domain.Activity;
import com.taobao.api.domain.Coupon;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.ItemCat;
import com.taobao.api.domain.Meal;
import com.taobao.api.domain.Promotion;
import com.taobao.api.domain.SellerCat;
import com.taobao.api.domain.Shop;
import com.taobao.api.request.ItemGetRequest;
import com.taobao.api.request.ItemUpdateRequest;
import com.taobao.api.request.ItemcatsGetRequest;
import com.taobao.api.request.ItemsListGetRequest;
import com.taobao.api.request.ItemsOnsaleGetRequest;
import com.taobao.api.request.ItemsSearchRequest;
import com.taobao.api.request.MarketingPromotionsGetRequest;
import com.taobao.api.request.PromotionActivityGetRequest;
import com.taobao.api.request.PromotionCouponsGetRequest;
import com.taobao.api.request.PromotionMealGetRequest;
import com.taobao.api.request.SellercatsListGetRequest;
import com.taobao.api.request.ShopGetRequest;
import com.taobao.api.request.TimeGetRequest;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.request.VasSubscribeGetRequest;
import com.taobao.api.response.ItemGetResponse;
import com.taobao.api.response.ItemUpdateResponse;
import com.taobao.api.response.ItemcatsGetResponse;
import com.taobao.api.response.ItemsListGetResponse;
import com.taobao.api.response.ItemsOnsaleGetResponse;
import com.taobao.api.response.ItemsSearchResponse;
import com.taobao.api.response.MarketingPromotionsGetResponse;
import com.taobao.api.response.PromotionActivityGetResponse;
import com.taobao.api.response.PromotionCouponsGetResponse;
import com.taobao.api.response.PromotionMealGetResponse;
import com.taobao.api.response.SellercatsListGetResponse;
import com.taobao.api.response.ShopGetResponse;
import com.taobao.api.response.TimeGetResponse;
import com.taobao.api.response.UserGetResponse;
import com.taobao.api.response.VasSubscribeGetResponse;

public class Taobao implements StoreService, SubscribeService {

	private static Logger logger = Logger.getLogger(Taobao.class);
	private static SimpleDateFormat sdf = new SimpleDateFormat(
			"yyyy-MM-dd HH:mm:ss");

	private static SimpleDateFormat _sdf = new SimpleDateFormat(
	"yyyy-MM-dd");
	
	private static DecimalFormat df = new DecimalFormat("0.00");

	private static StoreService instance = new Taobao();

	private Configuration configuration;
	private SystemErrorCode systemErrorCode;

	public SystemErrorCode getSystemErrorCode() {
		return systemErrorCode;
	}

	public void setSystemErrorCode(SystemErrorCode systemErrorCode) {
		this.systemErrorCode = systemErrorCode;
	}

	private Taobao() {
	}

	private void initialize() {
	}

	public static StoreService getInstance() {
		return instance;
	}

	public Configuration getConfiguration() {
		return configuration;
	}

	public void setConfiguration(Configuration configuration) {
		this.configuration = configuration;
	}

	public String getAuthUrl() {
		return configuration.getTaobaoOauthPath();
	}

	
	public Object getUser(String sessionKey) throws MarketingExpertException {
		TaobaoClient client = new DefaultTaobaoClient(configuration.getTabbaoApipath(), configuration.getTaobaoAppKey(), configuration.getTabbaoAppSecret());
		UserGetRequest req = new UserGetRequest();
		req.setFields("user_id,uid,nick,type,sex,buyer_credit,seller_credit ,has_shop,created,last_visit,location");
		UserGetResponse response = null;
		try {
			response = client.execute(req, sessionKey); 
			
			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}
			return response.getUser();
		} catch (ApiException e) {
			logger.error("ErrorCode:" + e.getErrCode() + ",ErrorMessage"
					+ e.getMessage(), e);

			if (e.getErrCode().equalsIgnoreCase("27")
					|| e.getErrCode().equals("100")) {
				throw new MarketingExpertException("01", Resources
						.getString("InvalidSession"));
			} else {
				throw new MarketingExpertException(e);
			}
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	public Shop getUserShop(String nick) throws MarketingExpertException {
		TaobaoClient client = new DefaultTaobaoClient(configuration
				.getTabbaoApipath(), configuration.getTaobaoAppKey(),
				configuration.getTabbaoAppSecret());
		ShopGetRequest req = new ShopGetRequest();
		req
				.setFields("sid,cid,title,nick,desc,bulletin,pic_path,created,modified");
		ShopGetResponse response = null;

		req.setNick(nick);

		try {
			response = client.execute(req);
			this.checkResponseStatus(response);
			Shop shop = response.getShop();
			return shop;
		} catch (ApiException e) {
			logger.error(e.getErrMsg(), e);
			throw new MarketingExpertException(e);
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * ��ȡ�û��Ķ�����ϵ
	 */
	public List<ArticleUserSubscribe> getSubscribe(String nick)
			throws MarketingExpertException {

		TaobaoClient client = new DefaultTaobaoClient(configuration
				.getTabbaoApipath(), configuration.getTaobaoAppKey(),
				configuration.getTabbaoAppSecret());
		List<ArticleUserSubscribe> _articlesUserSubs = new ArrayList<ArticleUserSubscribe>();
		try {
			VasSubscribeGetRequest req = new VasSubscribeGetRequest();
			req.setNick(nick);
			req.setArticleCode(configuration.getAppArticleCode());
			VasSubscribeGetResponse response = client.execute(req);

			List<com.taobao.api.domain.ArticleUserSubscribe> articleUserSubscribe = response
					.getArticleUserSubscribes();

			for (com.taobao.api.domain.ArticleUserSubscribe aus : articleUserSubscribe) {
				ArticleUserSubscribe _aus = new ArticleUserSubscribe(aus
						.getItemCode(), sdf.format(aus.getDeadline()));
				_articlesUserSubs.add(_aus);
			}
			return _articlesUserSubs;
		} catch (ApiException e) {
			logger.error(Resources.getString("Taobao.getUserSubscribeFailed"),
					e);
			throw new MarketingExpertException(Resources
					.getString("Taobao.getUserSubscribeFailed"), e);
		}

	}

	/*
	 * ��ȡ��̨�����ҷ�����Ʒ�ı�׼��Ʒ��Ŀ * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getItemCat()
	 */
	public List<ItemCat> getItemCategory() throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			ItemcatsGetRequest req = new ItemcatsGetRequest();

			Date dateTime = SimpleDateFormat.getDateTimeInstance().parse(
					sdf.format(new Date()));
			req.setDatetime(dateTime);
			req.setParentCid(0L);
			ItemcatsGetResponse response = client.execute(req);
			return response.getItemCats();
		} catch (ApiException e) {
			logger.error("��ѯ������Ʒ��Ŀʧ��", e);
			throw new MailAuthenticationException(e);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new MarketingExpertException("����ʱ���ʧ��", e);
		}
	}

	/*
	 * ��ȡ��ǰ�û����ڳ���״̬����Ʒ�б�
	 * 
	 * @see com.marketingexpert.service.storemgnt.StoreService#getItemOnSale()
	 */
	public List<Item> getItemOnSale(long pageNo, String sessionKey)
			throws MarketingExpertException {

		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
			req
					.setFields("approve_status,num_iid,title,nick,type,cid,detail_url,pic_url,num,,list_time,price,delist_time,seller_cids,outer_id");
			req.setOrderBy("list_time:desc");
			req.setPageNo(pageNo);
			req.setPageSize(10L);
			ItemsOnsaleGetResponse response = client.execute(req, sessionKey);
			checkResponseStatus(response);
			return response.getItems();
		} catch (ApiException e) {
			logger.error("��ѯ�û�������Ʒʧ��", e);
			throw new MarketingExpertException("", e);
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	public void checkResponseStatus(TaobaoResponse response) {
		if (response.getErrorCode() != null) {
			String errorCode = response.getErrorCode();
			if (errorCode.equals(systemErrorCode.getInvalidSession())) {
				throw new MarketingExpertException(systemErrorCode
						.getInvalidSession(), Resources
						.getString("InvalidSession"));
			} else if (errorCode.equals(systemErrorCode.getiSPError())) {
				throw new MarketingExpertException(systemErrorCode
						.getiSPError(), Resources
						.getString("RemoteServerError"));
			} else {
				throw new MarketingExpertException(errorCode, Resources
						.getString("OtherErrorTip")
						+ response.getMsg());
			}
		}
	}

	/*
	 * ������ȡ��Ʒ
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getItem(java.lang.
	 * String[], java.lang.String)
	 */
	public List<Item> getItem(String[] iids, String sessionKey)
			throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			ItemsListGetRequest req = new ItemsListGetRequest();
			req
					.setFields("num_iid,title,nick,price,num,list_time,delist_time,location,approve_status,pic_url,detail_url");

			StringBuilder numIids = new StringBuilder();

			for (String iid : iids) {
				numIids.append(iid).append(",");
			}

			String iidss = numIids.substring(0, numIids.length() - 1)
					.toString();

			req.setNumIids(iidss);
			ItemsListGetResponse response = client.execute(req, sessionKey);

			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}

			return response.getItems();
		} catch (ApiException e) {
			logger.error("������ȡ��Ʒʧ��", e);
			throw new MarketingExpertException("", e);
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	/*
	 * �����ƷId��ȡ������Ʒ
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getSingleItem(java
	 * .lang.String, java.lang.String)
	 */
	public Item getSingleItem(long itemId, String sessionKey)
			throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			ItemGetRequest req = new ItemGetRequest();
			req
					.setFields("num_iid,title,nick,price,num,list_time,delist_time,location,approve_status,pic_url,detail_url");
			req.setNumIid(itemId);
			ItemGetResponse response = client.execute(req, sessionKey);

			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}

			return response.getItem();
		} catch (ApiException e) {
			throw new MarketingExpertException(e);
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	private String getSingleItemDetailUrl(long itemId, String sessionKey)
			throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			ItemGetRequest req = new ItemGetRequest();
			req.setFields("detail_url");
			req.setNumIid(itemId);
			ItemGetResponse response = client.execute(req, sessionKey);

			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}

			return response.getItem().getDetailUrl();
		} catch (ApiException e) {
			throw new MarketingExpertException(e);
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw e;
		}
	}

	/*
	 * ������Ʒ�۸�
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#updateItemPrice(java
	 * .lang.String, double)
	 */
	public void updateItemPrice(String itemId, double minusRMB,
			String sessionKey) throws MarketingExpertException {
		if (minusRMB <= 0) {
			return;
		}
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			Item item = this.getSingleItem(Long.parseLong(itemId), sessionKey);
			ItemUpdateRequest req = new ItemUpdateRequest();
			req.setNumIid(Long.parseLong(itemId));
			double minuscount = Double.parseDouble(item.getPrice()) - minusRMB;
			if (minuscount < 0) {
				minuscount = 0;
			}
			req.setPrice(String.valueOf(minuscount));
			req.setSkuPrices(df.format(minuscount) + "," + item.getPrice());

			ItemUpdateResponse response = client.execute(req, sessionKey);
		} catch (ApiException e) {
			logger
					.error(Resources.getString("Taobao.updateItemPriceFailed"),
							e);
			throw new MarketingExpertException(Resources
					.getString("Taobao.updateItemPriceFailed"), e);
		}
	}

	/*
	 * ��ȡ�����Զ�����Ŀ
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getSellercatsList(
	 * java.lang.String, java.lang.String)
	 */
	public List<SellerCat> getSellercatsList(String sessionKey, String nick)
			throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			SellercatsListGetRequest req = new SellercatsListGetRequest();
			req.setNick(nick);
			req.setFields("cid,name");
			SellercatsListGetResponse response = client.execute(req);
			return response.getSellerCats();
		} catch (ApiException e) {
			logger.error(Resources.getString("Taobao.getSellercatsListFailed"),
					e);
			throw new MarketingExpertException(Resources
					.getString("Taobao.getSellercatsListFailed"), e);
		}

	}

	/*
	 * ��Ʒ����
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#searchItem(java.lang
	 * .String, java.lang.String, java.lang.String, java.lang.String,
	 * java.lang.String)
	 */
	public Map<String, Object> searchItem(String nick, long pageNo,
			long pageSize, Map<String, String> parames)
			throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			ItemsSearchRequest req = new ItemsSearchRequest();
			req
					.setFields("num_iid,title,nick,price,num,approve_status,type,location,list_time,delist_time,pic_url,detail_url");

			if (parames.get("title") != null) {
				req.setQ(parames.get("title"));
			}

			if (parames.get("outerId") != null) {
				req.setQ(parames.get("outerId"));
			}

			if (parames.get("catId") != null) {
				req.setCid(Long.parseLong(parames.get("catId")));
			}

			if (parames.get("searchNumFrom") != null) {
				req
						.setStartVolume(Long.parseLong(parames
								.get("searchNumFrom")));
			}

			if (parames.get("searchNumTo") != null) {
				req.setEndPrice(Long.parseLong(parames.get("searchNumTo")));
			}

			if (parames.get("startPrice") != null) {
				req.setStartPrice(Long.parseLong(parames.get("startPrice")));
			}

			if (parames.get("endPrice") != null) {
				req.setEndPrice(Long.parseLong(parames.get("endPrice")));
			}

			if (parames.get("discount") != null) {
				req.setHasDiscount(Boolean
						.parseBoolean(parames.get("discount")));
			}

			req.setNicks(nick);
			req.setOrderBy("list_time:desc");
			req.setPageNo(pageNo);
			req.setPageSize(pageSize);
			ItemsSearchResponse response = client.execute(req);

			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}
			Long totalResult = response.getTotalResults();

			Map<String, Object> results = new HashMap<String, Object>();
			List<Item> items = null;
			if (response.getItemSearch() != null) {
				items = response.getItemSearch().getItems();
			}
			results.put("items", items);
			results.put("totalResults", totalResult);
			return results;
		} catch (ApiException e) {
			logger.error(Resources.getString("Taobao.getSellercatsListFailed"),
					e);
			throw new MarketingExpertException(Resources
					.getString("Taobao.getSellercatsListFailed"), e);
		} catch (MarketingExpertException e) {
			logger.error("errorCode:" + e.getErrCode() + "," + "errorMsg:"
					+ e.getMessage(), e);
			throw e;
		}

	}

	/*
	 * ��ȡjson��Ʒ json��ʽ����
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getNewItem(java.lang
	 * .String)
	 */
	public JSONArray getNewItemAsJson(long pageNo, String sessionKey) {

		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			List<Item> items = this.getItemOnSale(pageNo, sessionKey);

			if (items == null || items.size() < 1) {
				return JSONArray.fromObject("[]");
			}

			JSONArray jsonItems = JSONArray.fromObject(items);
			return jsonItems;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new MarketingExpertException(e.getMessage(), e);
		}
	}

	/*
	 * ��ȡ�������е��Żݾ�
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getExistCoupon(java
	 * .lang.String)
	 */
	public List<Coupon> getExistCoupon(String sessionKey, long pageNo,
			long couponId) throws MarketingExpertException {

		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			PromotionCouponsGetRequest req = new PromotionCouponsGetRequest();
			if (couponId != 0) {
				req.setCouponId(couponId);
			}
			if (pageNo != 0) {
				req.setPageNo(pageNo);
			}
			req.setPageSize(10L);
			PromotionCouponsGetResponse response = client.execute(req,
					sessionKey);

			if (response.getErrorCode() != null) {
				throw new MarketingExpertException(response.getErrorCode(),
						response.getMsg());
			}

			return response.getCoupons();

		} catch (ApiException e) {
			throw new MarketingExpertException(e.getErrMsg(), e.getErrCode());
		} catch (MarketingExpertException e) {
			logger.error(e.getErrCode() + ";" + e.getMessage(), e);
			throw e;
		}

	}

	/*
	 * & �Զ��Ƽ���������Ʒ
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#searchNewItem(java
	 * .lang.String, java.lang.String)
	 */
	public List<Item> searchNewItem(String sessionKey, String today)
			throws MarketingExpertException {
		TaobaoClient client = new DefaultTaobaoClient(configuration
				.getTabbaoApipath(), configuration.getTaobaoAppKey(),
				configuration.getTabbaoAppSecret());
		
		
		
		long pageNo = 1L;
		List<Item> returnItems = new ArrayList<Item>();
		try {
			
				Calendar c = Calendar.getInstance();
				Date end = sdf.parse(_sdf.format(c.getTime()) + " 20:00:00");
				
				c.add(Calendar.DATE, -1);
				
				Date _start = sdf.parse(_sdf.format(c.getTime()) + " 20:00:00");
				
			while (true) {
				List<Item> items = this.getItemOnSale(pageNo, sessionKey);
				if (items == null || items.size() <= 0) {
					return returnItems;
				}
				for (Item item : items) {
					if(item.getListTime().compareTo(_start) >= 0 && item.getListTime().compareTo(end) <= 0) {
						if (item.getApproveStatus().equals("onsale")) {
							try {
								Thread.sleep(5000);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

							item.setDetailUrl(this.getSingleItemDetailUrl(item
									.getNumIid(), sessionKey));

							returnItems.add(item);
						}
						continue;
					} else {
						continue;
					}
				}
				pageNo++;

				if (!_sdf.format(items.get(items.size() - 1).getListTime())
						.equals(today)) {
					break;
				}
			}
			return returnItems;
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage(), e);
			throw e;
		} catch (ParseException e) {
			logger.error(e.getMessage(), e);
			throw new MarketingExpertException(e);
		} 
	}

	/*
	 * ��ѯ�����Żݾ�
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getActivity(java.lang
	 * .String, java.lang.String)
	 */
	public List<Activity> getActivity(String activityId, String sessionKey)
			throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			PromotionActivityGetRequest req = new PromotionActivityGetRequest();

			if (activityId != null) {
				req.setActivityId(Long.parseLong(activityId));
			}

			PromotionActivityGetResponse response = client.execute(req,
					sessionKey);

			if (response.getErrorCode() != null) {
				throw new MarketingExpertException(response.getErrorCode(),
						response.getMsg());
			}

			return response.getActivitys();
		} catch (ApiException e) {
			logger.error(e.getErrMsg(), e);
			throw new MarketingExpertException(e.getErrCode(), e);
		} catch (MarketingExpertException e) {
			logger.error(e.getErrMsg(), e);
			throw e;
		}
	}

	/*
	 * ��json�������ʽ�����û����е�ȫ���
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#getActivityAsJson(
	 * java.lang.String, java.lang.String)
	 */
	public JSONArray getActivityAsJson(String activityId, String sessionKey)
			throws MarketingExpertException {

		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			List<Activity> activites = this.getActivity(null, sessionKey);

			if (activites != null && activites.size() > 0) {
				return JSONArray.fromObject("[]");
			} else {
				return JSONArray.fromObject(activites);
			}
		} catch (MarketingExpertException e) {
			logger.error(e.getMessage());
			throw new MarketingExpertException("", e);
		}

	}

	/*
	 * ������ѯ�
	 * 
	 * @see
	 * com.marketingexpert.service.storemgnt.StoreService#batchQueryActivity
	 * (java.lang.String[], java.lang.String)
	 */
	public List<AbstractActivity> getCouponActivity(String activityId,
			String sessionKey) throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			List<AbstractActivity> activities = new ArrayList<AbstractActivity>();
		
			PromotionActivityGetRequest req = new PromotionActivityGetRequest();
		
			if(activityId != null) {
				req.setActivityId(Long.parseLong(activityId));
			}
			
			PromotionActivityGetResponse response = client.execute(req,
					sessionKey);
			
			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}
			
			if(response.getActivitys() == null) {
				return null;
			}else if (response.getActivitys().size() > 0 && response.getActivitys().get(0) != null && activityId != null) {
				Coupon coupon = this.getExistCoupon(sessionKey, 0L,
						response.getActivitys().get(0).getCouponId()).get(0);
				AbstractActivity aa = new AbstractActivityTaobaoImpl(response
						.getActivitys().get(0), coupon);
				activities.add(aa);
			} else {
				for(int i=0; i<response.getActivitys().size(); i++) {
					Coupon coupon = this.getExistCoupon(sessionKey, 0L,
							response.getActivitys().get(0).getCouponId()).get(0);
					AbstractActivity aa = new AbstractActivityTaobaoImpl(response
							.getActivitys().get(i), coupon);
					activities.add(aa);
				}
			}

			return activities;

		} catch (ApiException e) {
			logger
					.error(Resources
							.getString("Taobao.batchQueryActivityFailed"));
			throw new MarketingExpertException(e);
		} catch (MarketingExpertException e) {
			logger.error("errorCode:" + e.getErrCode() + "," + "errorMsg:"
					+ e.getMessage(), e);
			throw e;
		}
	}

	/*
	 * ������ѯ�Żݾ�
	 */
	public List<Coupon> batchQueryCoupon(long[] couponIds, String sessionKey)
			throws MarketingExpertException {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			List<Coupon> coupons = new ArrayList<Coupon>();

			PromotionCouponsGetRequest req = new PromotionCouponsGetRequest();

			for (long couponId : couponIds) {

				req.setCouponId(couponId);

				PromotionCouponsGetResponse response = client.execute(req,
						sessionKey);

				if (response.getErrorCode() != null) {
					String errorCode = response.getErrorCode();
					if (errorCode.equals(systemErrorCode.getInvalidSession())) {
						throw new MarketingExpertException(systemErrorCode
								.getInvalidSession(), Resources
								.getString("InvalidSession"));
					} else if (errorCode.equals(systemErrorCode.getiSPError())) {
						throw new MarketingExpertException(systemErrorCode
								.getiSPError(), Resources
								.getString("RemoteServerError"));
					} else {
						throw new MarketingExpertException(errorCode, Resources
								.getString("OtherErrorTip")
								+ response.getMsg());
					}
				}

				if (response.getCoupons().size() > 0
						&& response.getCoupons().get(0) != null) {

					coupons.add(response.getCoupons().get(0));
				}
			}
			return coupons;

		} catch (ApiException e) {
			logger.error(e);
			throw new MarketingExpertException(e);
		} catch (MarketingExpertException e) {
			logger.error("errorCode:" + e.getErrCode() + "," + "errorMsg:"
					+ e.getMessage(), e);
			throw e;
		}
	}

	/**
	 * ��ȡ���̱������ۿ���Ϣ
	 */
	public MarketingPromotion getItemPromotion(String itemId,
			String sessionKey, long pageNo) {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			MarketingPromotionsGetRequest req = new MarketingPromotionsGetRequest();
			req
					.setFields("promotion_id, promotion_title, num_iid,promotion_desc,decrease_num,discount_value,discount_type,start_date,end_date,status,tag_id");
			req.setStatus("ACTIVE");
			req.setNumIid(itemId);
			MarketingPromotionsGetResponse response = client.execute(req,
					sessionKey);

			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}

			if (response.getPromotions() == null) {
				return null;
			}

			if (response.getPromotions().size() > 0) {
				this.logPromotion(response.getPromotions());// ������־
				Item item = this.getSingleItem(Long.parseLong(itemId),
						sessionKey);
				TaobaoItem ti = new TaobaoItem(item);

				MarketingPromotion mp = new TaobaoPromotion(response
						.getPromotions().get(0), ti);

				return mp;
			}
			return null;

		} catch (ApiException e) {
			logger.error(e.getErrMsg(), e);
			throw new MarketingExpertException(e.getErrCode(), e.getMessage());
		} catch (MarketingExpertException e) {
			logger.error(e.getErrMsg(), e);
			throw e;
		}
	}

	private void logPromotion(List<Promotion> promotions) {
		logger.warn("�����ۿ�:");
		for (Iterator<Promotion> it = promotions.iterator(); it.hasNext();) {
			Promotion p = it.next();
			logger.warn("����Id:" + p.getNumIid());
			logger.warn("�ۿ�id:" + p.getPromotionId());
			logger.warn("�ۿ۱���:" + p.getPromotionTitle());
			logger.warn("�Żݶ��:" + p.getDiscountValue());
			logger.warn("�Ż�����:" + p.getDiscountType());
			logger.warn("�Ż�����:" + p.getPromotionDesc());
			logger.warn("�Żݲ���״̬:" + p.getStatus());
			logger.warn("��Ӧ����Ⱥ��ǩ:" + p.getTagId());
			logger.warn("���ۼ���:" + p.getDecreaseNum());
		}
	}

	/**
	 * ��ѯ���������ײ�
	 */
	public List<Meal> queryMeals(long mealId, String sessionKey) {

		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			PromotionMealGetRequest req = new PromotionMealGetRequest();

			if (mealId > 0L) {
				req.setMealId(mealId);
			}
			req.setStatus("VALID");
			PromotionMealGetResponse response = client.execute(req, sessionKey);
			if (response.getErrorCode() != null) {
				String errorCode = response.getErrorCode();
				if (errorCode.equals(systemErrorCode.getInvalidSession())) {
					throw new MarketingExpertException(systemErrorCode
							.getInvalidSession(), Resources
							.getString("InvalidSession"));
				} else if (errorCode.equals(systemErrorCode.getiSPError())) {
					throw new MarketingExpertException(systemErrorCode
							.getiSPError(), Resources
							.getString("RemoteServerError"));
				} else {
					throw new MarketingExpertException(errorCode, Resources
							.getString("OtherErrorTip")
							+ response.getMsg());
				}
			}

			if (response.getMealList() == null
					|| response.getMealList().size() <= 0) {
				return null;
			}
			return response.getMealList();
		} catch (ApiException e) {
			logger.error(e);
			throw new MarketingExpertException(e.getErrCode(), e.getMessage());
		} catch (MarketingExpertException e) {
			throw e;
		}

	}

	@Override
	public Date getTBServerTime() {
		try {
			TaobaoClient client = new DefaultTaobaoClient(configuration
					.getTabbaoApipath(), configuration.getTaobaoAppKey(),
					configuration.getTabbaoAppSecret());
			TimeGetRequest req = new TimeGetRequest();
			TimeGetResponse response = client.execute(req);
			return response.getTime();
		} catch (ApiException e) {
			logger.error(e.getMessage(), e);
			return null;
		}
	}
}
